﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Kokomo
{
	public static class ObjectExtensions
	{
		public static int SizeOf(this object target)
		{
			ArgumentValidation.CheckNullArgument("target", target);
			return Marshal.SizeOf(target);
		}
		public static byte[] ToMarshaledByteArray(this object target)
		{
			ArgumentValidation.CheckNullArgument("target", target);
			ArgumentValidation.Cast<ValueType>("target", target);

			int size = target.SizeOf();

			IntPtr bufferPointer = Marshal.AllocCoTaskMem(size);
			byte[] buffer = new byte[size];
			try
			{
				Marshal.StructureToPtr(target, bufferPointer, false);
				Marshal.Copy(bufferPointer, buffer, 0, size);
			}
			finally
			{
				Marshal.FreeCoTaskMem(bufferPointer);
			}

			return buffer;
		}
		public static TStruct ToMarshaledStruct<TStruct>(this IntPtr target)
		{
			TStruct @struct = (TStruct)Marshal.PtrToStructure(target, typeof(TStruct));

			return @struct;
		}
	}
}
